package house;

public class HouseManagement {
	private House[] houses;

	public HouseManagement() {
		this.houses = new House[10];
	}

	public HouseManagement(int size) {
		super();
		this.houses = new House[size];
	}
	private int getUsefulIndex(){
		for (int i = 0; i < houses.length; i++) {
		if(null == houses[i]){
				return i;
			}
		}
		return -1;
	}
	public boolean save(House house){
		int index = getUsefulIndex();
		if(-1 == index){
			return false;
		}else{
			houses[index] = house;
			return true;
		}
	}
	public boolean rent(House house){
		for (int i = 0; i < houses.length && houses[i] != null; i++) {
			if(house.getId() == houses[i].getId()){
				if(!houses[i].isRent()){
					houses[i].setRent(true);
					return true;
				}
			}
		}
		return false;
	}
	public boolean delete(House house){
		for (int i = 0; i < houses.length && houses[i] != null; i++) {
			if(houses[i].getId() == house.getId()){
				int j;
				for(j = i+1;j < houses.length && houses[j] != null;j++){
					houses[j-1] = houses[j];
				}
				houses[j-1] = null;
				return true;
			}
		}
		return false;
	}
	public boolean back(House house){
		for (int i = 0; i < houses.length && houses[i] != null; i++) {
			if(house.getId() == houses[i].getId()){
				if(houses[i].isRent()){
					houses[i].setRent(false);
					return true;
				}
			}		
		}
		return false;
	}
	public House selectById(House house){
		for (int i = 0; i < houses.length && houses[i]!=null; i++) {
			if(houses[i].getId() == houses.length){
				return houses[i];
			}
		}
		return null;
	}
	public House[] selectByType(House house){
		House[] house2 = new House[houses.length];
		int index = getUsefulIndex();
		for(int i = 0, j = 0; i<index; i++){
			if(houses[i].getType().equals(house.getType())){
				house2[j++] = houses[i];
			}
		}
		return house2;
		
	}
	public House[] selectByPrice(int low,int high){

		House[] house2 = new House[10];
		for(int i = 0,j = 0;i<houses.length && houses[i] != null;i++){
			if(houses[i].getPrice()>=low && houses[i].getPrice()<=high){
				 house2[j++] = houses[i];
			}
		}
		return house2;
	}

	public House[] selectAll(){
		return houses;
	}	




	public House[] selectByArea(double lowerArea,double highArea){
		House[] house2 = new House[houses.length];
		for(int i = 0,j = 0;i<houses.length && houses[i] != null;i++){
			if(houses[i].getArea()>=lowerArea && houses[i].getArea()<=highArea){
				 house2[j++] = houses[i];
			}
		}
		return house2;
	}
	
	public House[] selectByLocation(String location){
		House[] house2 = new House[houses.length];
		int index = getUsefulIndex();
		for(int i = 0, j = 0; i<index; i++){
			if(houses[i].getLocation().equals(location)){
				house2[j++] = houses[i];
			}
		}
		return house2;
	}
	
}
